package com.waypolice.manager.controller;

import com.waypolice.base.BaseController;
import com.waypolice.common.constant.BorrowConstant;
import com.waypolice.common.constant.CmsResult;
import com.waypolice.common.utils.*;
import com.waypolice.manager.service.*;
import com.waypolice.pojo.*;
import com.waypolice.pojo.vo.CmsBorRegisterVo;
import com.waypolice.pojo.vo.Variable;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 描述:
 *
 * @author zyp
 * @description 借阅审核action
 * @create 2019-03-12 9:54
 */
@Controller
@Api(value = "借阅审核控制器", description = "查看审核历史、我的待审核、我审核的项目等")
@RequestMapping(value="/pcwindow")
public class BorrowAuditAction extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BorrowAuditAction.class);

    @Value("${IMAGE_SERVER_URL}")
    private String IMAGE_SERVER_URL;

    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    protected TaskService taskService;

    @Autowired
    protected HistoryService historyService;

    @Autowired
    protected RepositoryService repositoryService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    protected BorAuditService borAuditService;

    @Autowired
    protected UserService userService;

    @Autowired
    protected ActDefineService actDefineService;

    @Autowired
    protected BorRegisterService borRegisterService;

    @Autowired
    public UpmsDictionaryService upmsDictionaryService;

    @Autowired
    public UpmsOrganizationService upmsOrganizationService;


    /**
     * @author:zyp
     * @description 借阅管理跳转
     * @date: 2019/4/2 16:27
     * @return 
     */
    @ApiOperation(value = "借阅管理跳转")
    @RequiresPermissions("cms:borAudit:read")
    @RequestMapping(value = "/toBorAudit")
    public String jumpToBorrowPage(HttpServletRequest req){
        return "/borrowManager/borrowAudit";
    }

    /**
     * @author:zyp
     * @description 查看借阅代办事务列表
     * @date: 2019/3/12 11:20
     * @return 
     */
    @ApiOperation(value = "借阅待办事务列表")
    @RequiresPermissions("cms:borAudit:myAudit")
    @RequestMapping(value="/getMyAudit")
    @ResponseBody
    public Object getMyAudit(@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                               @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
                             HttpServletRequest httpServletRequest){
        Properties properties = ReadProperties.getProperties("activiti.properties");
        String activitiTypeParam = httpServletRequest.getParameter("activitiType");
        String activitiType = properties.getProperty(activitiTypeParam);
        List<CmsBorRegisterVo> results = new ArrayList();
        //获取当前登录人的账号
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        //根据用户id查找 是否有此用户
        User nameUser = identityService.createUserQuery().userFirstName(username).singleResult();
        List<Task> allTasks = new ArrayList<>();
        //因assigness输入的为账号的名字 而组是根据用户id绑定
        //这就造成了当审批人为用户名时，应用taskCandidateOrAssigned方法无法获取，需要使用
        TaskQuery groupTaskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(nameUser.getId());
        List<Task> groupTasks = groupTaskQuery.list();
        allTasks.addAll(groupTasks);
        TaskQuery assignedTaskQuery = taskService.createTaskQuery().taskCandidateOrAssigned(username);
        allTasks.addAll(assignedTaskQuery.list());
        // 根据流程的业务ID查询实体并关联
        for (Task task : allTasks) {
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
            if (processInstance == null) {
                continue;
            }
            String businessKey = processInstance.getBusinessKey();
            if (businessKey == null||"null".equals(businessKey)) {
                continue;
            }
            CmsBorRegisterVo cmsBorRegisterVo = borAuditService.getBorRegisterVoByIdAndActType(new Long(businessKey),activitiType);
            if(cmsBorRegisterVo==null){
                continue;
            }
            String taskid = task.getId();
            cmsBorRegisterVo.setTaskId(taskid);
            cmsBorRegisterVo.setTaskAssignee(task.getAssignee());
            cmsBorRegisterVo.setCreateTime(task.getCreateTime());
            cmsBorRegisterVo.setTaskDefinitionKey(task.getTaskDefinitionKey());
            cmsBorRegisterVo.setTaskName(task.getName());
            UpmsUser upmsUser = userService.selectUpmsUserByUserId(cmsBorRegisterVo.getBorUserId());
            if(upmsUser!=null){
                cmsBorRegisterVo.setBorUserName(upmsUser.getRealname());
            }
            //记录登记部门id
            if (cmsBorRegisterVo.getBorDeptId()!=null){
                UpmsOrganization upmsOrganization = upmsOrganizationService.getOrganizationById(cmsBorRegisterVo.getBorDeptId());
                cmsBorRegisterVo.setBorDeptName(upmsOrganization.getName());
            }
            // 设置当前任务信息
            cmsBorRegisterVo=borAuditService.getFileInfoByRegistId(cmsBorRegisterVo);
            cmsBorRegisterVo.setProcessId(processInstance.getId());
            cmsBorRegisterVo.setProcessDefinitionId(processInstance.getProcessDefinitionId());
            cmsBorRegisterVo.setSuspended(processInstance.isSuspended());
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult();
            cmsBorRegisterVo.setActVersion(processDefinition.getVersion());
            results.add(cmsBorRegisterVo);
        }
        //最终的list集合
        List<CmsBorRegisterVo> finalList = new ArrayList<CmsBorRegisterVo>();
        PageUtils<CmsBorRegisterVo> pageUtils = new PageUtils<CmsBorRegisterVo>();
        finalList = pageUtils.pageList(results,offset,limit);
        Map<String,Object> parameterMap = new HashedMap();
        parameterMap.put("rows",finalList);
        parameterMap.put("total",results.size());
        return parameterMap;
    }


    /**
     * @author:zyp
     * @description 查看运行中的流程
     * @date: 2019/3/12 11:56
     * @return
     */
    @ApiOperation(value = "查看运行中的流程")
    @RequiresPermissions("cms:borAudit:myRun")
    @RequestMapping(value = "/findRunningProcessInstaces")
    @ResponseBody
    public Object findRunningProcessInstaces(@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                                             @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
                                             HttpServletRequest httpServletRequest) {
        Properties properties = ReadProperties.getProperties("activiti.properties");
        String activitiTypeParam = httpServletRequest.getParameter("activitiType");
        String activitiType = properties.getProperty(activitiTypeParam);
        //获取当前登录人的用户id（账号）
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        //后续获取用户对象
        List<UpmsUser> users = userService.findByName(username);
        UpmsUser user = new UpmsUser();
        if(users!=null&&users.size()>0){
            user = users.get(0);
        }
        //获取当前用户的userId
        long userId = (long)user.getUserId();
        List<CmsBorRegisterVo> results = new ArrayList<CmsBorRegisterVo>();
        List<UpmsDictionary> upmsDictionaries = upmsDictionaryService.getUpmsDictionaryByCode("activitiCode");
        List<String> borCodeList = new ArrayList<>();
        for (UpmsDictionary upmsDictionary:upmsDictionaries){
            String code = upmsDictionary.getCode();
            if(activitiType.contains(code)){
                borCodeList.add(code);
            }
        }
        List<UpmsActDefine> upmsActDefines = actDefineService.getDefineByCodes(borCodeList);
        List<ProcessInstance> allList = new ArrayList<ProcessInstance>();
        //获取的key遍历 从中获取运行的内容,因工作流定义时 有可能遇见同一个key被定义两次（其中一次有可能为锁定状态）
        // 只是获取到的工作流实例会重复，故进行去重处理
        List<String> delRepeat = new ArrayList<>();
        for (UpmsActDefine upmsActDefine : upmsActDefines){
            String key = upmsActDefine.getAdKey();
            if(delRepeat.contains(key)){
                continue;
            }else{
                ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery().processDefinitionKey(key).active().orderByProcessInstanceId().desc();
                List<ProcessInstance> list = query.list();
                allList.addAll(list);
                delRepeat.add(key);
            }
        }
        // 关联业务实体
        for (ProcessInstance processInstance : allList) {
            String businessKey = processInstance.getBusinessKey();
            if (StringUtils.isBlank(businessKey)||"null".equals(businessKey)) {
                continue;
            }
            CmsBorRegisterVo cmsBorRegisterVo  = borAuditService.getBorRegisterVoByIdAndActType(MathUtils.string2long(businessKey),activitiType);
            //查看当前借阅用户是否为当前用户，若不是，则继续下一个内容
            if(cmsBorRegisterVo==null||cmsBorRegisterVo.getBorUserId()!= userId){
                continue;
            }
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult();
            cmsBorRegisterVo.setActVersion(processDefinition.getVersion());
            cmsBorRegisterVo=borAuditService.getFileInfoByRegistId(cmsBorRegisterVo);
            // 设置当前任务信息
            List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).active().orderByTaskCreateTime().desc().listPage(0, 1);
            Task task = tasks.get(0);
            List<IdentityLink> links = taskService.getIdentityLinksForTask(task.getId());
            String type = links.get(0).getType();
            if("assignee".equals(type)){
                String assignee = task.getAssignee();
                if(StringUtils.isNotBlank(assignee)){
                    UpmsUser upmsUser = userService.selectUpmsUserByUserId(MathUtils.string2long(assignee));
                    if(upmsUser!=null){
                        cmsBorRegisterVo.setTaskAssignee(upmsUser.getRealname());
                    }else{
                        List<UpmsUser> byName = userService.findByName(assignee);
                        if(byName!=null&&byName.size()>0){
                            cmsBorRegisterVo.setTaskAssignee(byName.get(0).getRealname());
                        }else{
                            cmsBorRegisterVo.setTaskAssignee(assignee);
                        }
                    }
                }else{
                    List<UpmsUser> byName = userService.findByName(task.getAssignee());
                    if(byName!=null&&byName.size()>0){
                        cmsBorRegisterVo.setTaskAssignee(byName.get(0).getRealname());
                    }else{
                        cmsBorRegisterVo.setTaskAssignee(task.getAssignee());
                    }
                }
            }else if ("candidate".equals(type)){
                String groupId = links.get(0).getGroupId();
                if(StringUtils.isNotBlank(groupId)){
                    StringBuilder sb = new StringBuilder();
//                    Group group = identityService.createGroupQuery().groupId(groupId).singleResult();
                    List<User> list = identityService.createUserQuery().memberOfGroup(groupId).list();
//                    if(group!=null){
//                        String id = group.getId();
//                        cmsBorRegisterVo.setTaskAssignee(group.getName());
//                    }
                    if(list!=null&&list.size()>0){
                        for (User auditUser : list){
                            sb.append(auditUser.getLastName()+",");
                        }
                        cmsBorRegisterVo.setTaskAssignee(sb.toString().substring(0,sb.toString().lastIndexOf(",")));
                    }
                }else{
                    StringBuilder sb = new StringBuilder();
                    for (IdentityLink il : links){
                        List<UpmsUser> byName = userService.findByName(il.getUserId());
                        if(byName!=null&&byName.size()>0){
                            sb.append(byName.get(0).getRealname()+",");
                        }
                    }
                    cmsBorRegisterVo.setTaskAssignee(sb.toString().substring(0,sb.toString().lastIndexOf(",")));
                }
            }
            cmsBorRegisterVo.setTaskId(task.getId());
            cmsBorRegisterVo.setCreateTime(task.getCreateTime());
            cmsBorRegisterVo.setTaskDefinitionKey(task.getTaskDefinitionKey());
            cmsBorRegisterVo.setTaskName(task.getName());
            cmsBorRegisterVo.setProcessId(processInstance.getId());
            cmsBorRegisterVo.setProcessDefinitionId(processInstance.getProcessDefinitionId());
            cmsBorRegisterVo.setSuspended(processInstance.isSuspended());
            results.add(cmsBorRegisterVo);
        }
        //最终的list集合
        List<CmsBorRegisterVo> finalList = new ArrayList<CmsBorRegisterVo>();
        PageUtils<CmsBorRegisterVo> pageUtils = new PageUtils<CmsBorRegisterVo>();
        finalList = pageUtils.pageList(results,offset,limit);
        Map<String,Object> parameterMap = new HashedMap();
        parameterMap.put("rows",finalList);
        parameterMap.put("total",results.size());
        return parameterMap;
    }

    /**
     * @author:zyp
     * @description 查看结束的流程
     * @date: 2019/3/12 13:41
     * @return
     */
    @ApiOperation(value = "查看结束的流程")
    @RequiresPermissions("cms:borAudit:myHistory")
    @RequestMapping(value = "/findFinishedProcessInstaces")
    @ResponseBody
    public Object findFinishedProcessInstaces(@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                                              @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
                                              HttpServletRequest httpServletRequest) {

        Properties properties = ReadProperties.getProperties("activiti.properties");
        String activitiTypeParam = httpServletRequest.getParameter("activitiType");
        String activitiType = properties.getProperty(activitiTypeParam);
        //获取当前登录人的用户id（账号）
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipal();
        List<UpmsUser> users = userService.findByName(username);
        UpmsUser user = new UpmsUser();
        if(users!=null&&users.size()>0){
            user = users.get(0);
        }
        //获取当前用户的userId
        long userId = (long)user.getUserId();
        List<CmsBorRegisterVo> results = new ArrayList<CmsBorRegisterVo>();
        List<UpmsDictionary> upmsDictionaries = upmsDictionaryService.getUpmsDictionaryByCode("activitiCode");
        List<String> borCodeList = new ArrayList<>();
        for (UpmsDictionary upmsDictionary:upmsDictionaries){
            String code = upmsDictionary.getCode();
            if(activitiType.contains(code)){
                borCodeList.add(code);
            }
        }
        List<UpmsActDefine> upmsActDefines = actDefineService.getDefineByCodes(borCodeList);
        List<HistoricProcessInstance> allList = new ArrayList<HistoricProcessInstance>();
        //获取的key遍历 从中获取运行的内容
        //获取的key遍历 从中获取运行的内容,因工作流定义时 有可能遇见同一个key被定义两次（其中一次有可能为锁定状态）
        // 只是获取到的工作流实例会重复，故进行去重处理
        List<String> delRepeat = new ArrayList<>();
        for (UpmsActDefine upmsActDefine : upmsActDefines){
            String key = upmsActDefine.getAdKey();
            if(delRepeat.contains(key)){
                continue;
            }else{
                HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery().processDefinitionKey(upmsActDefine.getAdKey()).finished().orderByProcessInstanceEndTime().desc();
                List<HistoricProcessInstance> list = query.list();
                allList.addAll(list);
                delRepeat.add(key);
            }
        }
        // 关联业务实体
        for (HistoricProcessInstance historicProcessInstance : allList) {
            String businessKey = historicProcessInstance.getBusinessKey();
            //逻辑变更   我的历史记录增加对我的审批的所有流程显示
//            CmsBorRegisterVo cmsBorRegisterVo = borAuditService.getBorRegisterVoById(Long.parseLong(businessKey));
            CmsBorRegisterVo cmsBorRegisterVo = borAuditService.getMyAuditRegister(Long.parseLong(businessKey),userId);
            //查看当前借阅用户是否为当前用户，若不是，则继续下一个内容
            if(cmsBorRegisterVo==null){
                continue;
            }
            UpmsUser upmsUser = userService.selectUpmsUserByUserId(cmsBorRegisterVo.getBorUserId());
            cmsBorRegisterVo.setBorUserName(upmsUser.getRealname());
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(historicProcessInstance.getProcessDefinitionId()).singleResult();
            cmsBorRegisterVo.setActVersion(processDefinition.getVersion());
            cmsBorRegisterVo =borAuditService.getFileInfoByRegistId(cmsBorRegisterVo);
            //任务的启动时间
            cmsBorRegisterVo.setTaskCreateTime(historicProcessInstance.getStartTime());
            //任务的结束时间
            cmsBorRegisterVo.setTaskFinishTime(historicProcessInstance.getEndTime());
            //临时将该自动充当为结束原因字段
            cmsBorRegisterVo.setBorPurpose(historicProcessInstance.getDeleteReason());
            cmsBorRegisterVo.setProcessDefinitionId(historicProcessInstance.getId());
            results.add(cmsBorRegisterVo);
        }
        //最终的list集合
        List<CmsBorRegisterVo> finalList = new ArrayList<CmsBorRegisterVo>();
        PageUtils<CmsBorRegisterVo> pageUtils = new PageUtils<CmsBorRegisterVo>();
        finalList = pageUtils.pageList(results,offset,limit);
        Map<String,Object> parameterMap = new HashedMap();
        parameterMap.put("rows",finalList);
        parameterMap.put("total",results.size());
        return parameterMap;
    }


    /**
     * @author zyp
     * @description 同意借阅申请
     * @date 2018/5/4 9:43
     * @param
     * @return
     */
    @ApiOperation(value = "同意借阅申请")
    @RequiresPermissions("cms:borAudit:read")
    @RequestMapping(value = "/borAuditResult")
    @ResponseBody
    public Object borPoss(String taskId, Variable var, Long borId, String auditUserView, Long taskType,String userName,String delegateUser){
        try {
            //获取当前登录人的用户id（账号）
            Subject subject = SecurityUtils.getSubject();
            String username = (String) subject.getPrincipal();
            List<UpmsUser> users = userService.findByName(username);
            UpmsUser user = new UpmsUser();
            if(users!=null&&users.size()>0){
                user = users.get(0);
            }
            Map<String, Object> variables = var.getVariableMap();
            boolean flag = (boolean)variables.get(var.getKeys());
            CmsBorAuditing cmsBorAuditing = new CmsBorAuditing();
            //修改时间
            Date now = DateTimeUtil.getNow();
            cmsBorAuditing.setCreateTime(now);
            cmsBorAuditing.setBorRegisterId(borId);
            cmsBorAuditing.setAuditUserId((long)user.getUserId());
            cmsBorAuditing.setAuditType(taskType);
            if(flag){
                cmsBorAuditing.setResultType(BorrowConstant.AUDIT_RESULT_TRUE);
                if(auditUserView==null||"".equals(auditUserView)){
                    cmsBorAuditing.setAuditUserView("同意");
                }else{
                    cmsBorAuditing.setAuditUserView(auditUserView);
                }
                //如果流程具有 指定表达式，则替换改表达式
                if(StringUtils.isNotBlank(delegateUser)){
                    variables.put(delegateUser,userName);
                }
            }else{
                cmsBorAuditing.setResultType(BorrowConstant.AUDIT_RESULT_FALSE);
                if(auditUserView==null||"".equals(auditUserView)){
                    cmsBorAuditing.setAuditUserView("驳回");
                }else{
                    cmsBorAuditing.setAuditUserView(auditUserView);
                }
            }
            cmsBorAuditing.setAuditIndex(System.currentTimeMillis()/1000);
            borAuditService.insert(cmsBorAuditing);
            taskService.complete(taskId, variables);
            return new CmsResult(1,"success",0);
        } catch (Exception e) {
            logger.error("error on complete task {}, variables={}", new Object[]{taskId, var.getVariableMap(), e});
            return "error";
        }
    }

    /**
     * @author zyp
     * @description 重新发起借阅申请
     * @date 2018年5月11日10:00:30
     * @param
     * @return
     */
    @ApiOperation(value = "重新发起借阅申请")
    @RequestMapping(value = "/modifyBorAudit")
    @ResponseBody
    public Object modifyBorAudit(@RequestParam(value="file",required=false)MultipartFile file ,HttpServletRequest request){
        //获取参数
        String taskId = request.getParameter("taskId");
        String keys = request.getParameter("keys");
        String values = request.getParameter("values");
        String types = request.getParameter("types");
        String taskType = request.getParameter("taskType");
        Variable var = new Variable(keys,values,types);
        CmsBorRegister cmsBorRegister = new CmsBorRegister();
        cmsBorRegister.setId(request.getParameter("borId")==null?null:Long.parseLong(request.getParameter("borId")));
        cmsBorRegister.setBorDeptDescription(request.getParameter("borDeptDescription"));
        cmsBorRegister.setBorType(request.getParameter("borType")==null?null:Long.parseLong(request.getParameter("borType")));
        cmsBorRegister.setBorTime(request.getParameter("borTime")==null?null:DateTimeUtil.strToDate(request.getParameter("borTime")));
        cmsBorRegister.setPlanReturnTime(request.getParameter("planReturnTime")==null?null:DateTimeUtil.strToDate(request.getParameter("planReturnTime")));
        cmsBorRegister.setBorPurpose(request.getParameter("borPurpose"));
        cmsBorRegister.setBorDeptId(request.getParameter("borDeptId")==null?null:Long.parseLong(request.getParameter("borDeptId")));
        cmsBorRegister.setRenewPurpose(request.getParameter("renewPurpose")==null?null:request.getParameter("renewPurpose"));
        cmsBorRegister.setRenewReturnTime(request.getParameter("renewReturnTime")==null?null:DateTimeUtil.strToDate(request.getParameter("renewReturnTime")));
        //当动态制定时应用
        String userName = request.getParameter("userName");
        String delegateUser = request.getParameter("delegateUser");
        try {
            //获取当前登录人的用户id（账号）
            Subject subject = SecurityUtils.getSubject();
            String username = (String) subject.getPrincipal();
            /*** 后续再进行逻辑处理 ***/
            List<UpmsUser> users = userService.findByName(username);
            UpmsUser user = new UpmsUser();
            if(users!=null&&users.size()>0){
                user = users.get(0);
            }
            Map<String, Object> variables = var.getVariableMap();
            boolean flag = (boolean)variables.get(var.getKeys());
            CmsBorAuditing cmsBorAuditing = new CmsBorAuditing();
            //修改时间
            Date now = DateTimeUtil.getNow();
            cmsBorAuditing.setCreateTime(now);
            cmsBorAuditing.setBorRegisterId(cmsBorRegister.getId());
            cmsBorAuditing.setAuditUserId((long)user.getUserId());
            cmsBorAuditing.setAuditType(Long.parseLong(taskType));
            cmsBorAuditing.setAuditUserView("重新发起流程");
            cmsBorAuditing.setResultType(BorrowConstant.AUDIT_RESULT_TRUE);
            //如果当前修改为无组织机构 且进行了文件的修改
            if(file!=null){
                // 取扩展名
                String originalFilename = file.getOriginalFilename();
                String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
                // 上传到图片服务器
                FastDfsClient fastDFSClient = new FastDfsClient("classpath:client.conf");
                String fastDfSUrl = fastDFSClient.uploadFile(file.getBytes(),extName);
                String imagesUrl = IMAGE_SERVER_URL + fastDfSUrl;
                cmsBorRegister.setBorAttestUrl(imagesUrl);

                CmsBorRegister oldCmsBorRegister = borRegisterService.getRegistById(Long.parseLong(request.getParameter("borId")));
                String oldUrl = oldCmsBorRegister.getBorAttestUrl();
                //删除曾经的照片
                fastDFSClient.deleteFile(oldUrl.replace(IMAGE_SERVER_URL,""));
            }cmsBorAuditing.setAuditIndex(System.currentTimeMillis()/1000);

            //如果流程具有 指定表达式，则替换改表达式
            if(StringUtils.isNotBlank(delegateUser)){
                variables.put(delegateUser,userName);
            }
            borRegisterService.updateByPrimaryKeySelective(cmsBorRegister);
            borAuditService.insert(cmsBorAuditing);
            taskService.complete(taskId, variables);
            return new CmsResult(1,"success",0);
        } catch (Exception e) {
            logger.error("error on complete task {}, variables={}", new Object[]{taskId, var.getVariableMap(), e});
            return "error";
        }
    }


    /**
     * @author:zyp
     * @description 获得详细的驳回资料
     * @date: 2019/3/20 17:02
     * @return 
     */
    @ApiOperation(value = "获得详细的驳回资料")
    @RequestMapping(value = "/getModifyAppliInfo")
    @ResponseBody
    public Object getModifyAppliInfo( Long borId){
        CmsBorAuditing cmsBorAuditing = borAuditService.getModifyAppliInfo(borId);
        UpmsUser upmsUser = userService.selectUpmsUserByUserId(cmsBorAuditing.getAuditUserId());
        cmsBorAuditing.setExtend1(upmsUser.getRealname());
        return cmsBorAuditing;
    }

    /**
     * @author:zyp
     * @description 根据借阅id，获取借阅的文件信息
     * @date: 2019/4/18 16:19
     * @return 
     */
    @ApiOperation(value = "根据借阅id，获取借阅的文件信息")
    @RequestMapping(value = "/getBorrowInfoByBorId")
    @ResponseBody
    public Object getBorrowInfoByBorId(	@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                                           @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
                                           @RequestParam(required = false, value = "sort") String sort,
                                           @RequestParam(required = false, value = "order") String order,
                                           @RequestParam(required = false, value = "borId") long borId){

        Map<String, Object> result=borAuditService.getBorrowInfoByBorId(offset, limit, sort, order,borId);
        return result;
    }

}